/**
 *  @author yinghui.zhang   证书到期提醒信息模块管理
 */
 
Ext.ns("cn.hls.web.action.dict");
var listView =cn.hls.web.action.dict.certSetView;

listView = function() {
	var  store, grid, formPanel, win;
	var fields =["id","certName", 'certCode',"expireWarn","warnInterval","preMonth","warnType"];
	var sm =  new Ext.grid.CheckboxSelectionModel({ singleSelect: true });
	return {
		init : function() {
			
            //------------------------------------------------- store
            store = this.createStore();
            //查询条件
			store.on('beforeload', function() {
				if(queryRole){
					this.baseParams = {
						"name" : Ext.getCmp('certSet_name').getValue()
						 
					};
				}
			});
            
			//------------------------------------------------- grid
			grid = this.createGrid();
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					listView.editInit();
				});
			}
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			                if(cellIndex>1){
				                var cell = view.getCell(rowIndex, cellIndex);  
		                        tip.body.dom.innerHTML = cell.innerHTML;  
			                }else{
			                	return false;
			                }
			            }  
			        }  
			    });  
			}); 
			
			// ------------------------------------------------- viewport
			new Ext.Viewport({ 
			      layout : 'fit',
				  items : [grid]
			});
			this.queryResItem();
		},
		
		createStore : function() {
			return new FrameWorkStore({
			     url : '/certSet/list.action',
			     fields : fields
		    });
		},
		
		createGrid : function() {
			return new ExtGrid({
						store : store,
						title : '<div class="panelTitleCss">证书到期提醒信息列表</div>',
						sm : sm  ,
						columnLines:true,//显示列表的竖分格线
						columns : [
					        new Ext.grid.RowNumberer(), 
					        sm ,
					        { sortable : true,dataIndex : "certName",autoWidth:true,header : "证书名称",width:100,align:'center'},
					        { sortable : true,dataIndex : "certCode",autoWidth:true,header : "证书代码",width:80,align:'center'},
					        { sortable : true,dataIndex : "expireWarn",autoWidth:true,header : "是否提醒",width:65,align:'center'},
					        { sortable : true,dataIndex : "warnInterval",autoWidth:true,header : "提醒间隔",width:65,align:'center'},
					        { sortable : true,dataIndex : "preMonth",autoWidth:true,header : "提前提醒(月)",width:85,align:'center'},
						    {sorttable:true,dataIndex:'warnType',autoWidth:true,width:120,header:'提醒人员',align:'center',
					        	renderer:function(val){
					        		if(val==null){
					        			return '';
					        		}else{
					        			var s=val.split(',');
					        			var data='';
					        			for(var i=0;i<s.length;i++){
					        				if(s[i]==1){
					        					data+='企业法人 '+" ";
					        				}else if(s[i]==2){
					        					data+='安管人员'+ " ";
					        				}else if(s[i]==3){
					        					data+='证书持有者'+" ";
					        				}
					        			}
					        			return data;
					        		}
					        	}},
						    {sorttable:true,dataIndex:'createTime',autoWidth:true,width:100,header:'创建时间',
						    	type:'date',renderer : function(val){
						    		if(val!=null){
						    			return new Date(val).dateFormat('Y-m-d');
						    		}
						    	},align:'center'}
						],
						tbar : listView.createTbar(),
						bbar : {
						    id : 'page',
							xtype : 'pageinfobar',
							pageSize : 20,
							store : store,
							pageMethod : listView.queryResItem
						}
					});
		},
		
		createTbar : function() {
			if(queryRole){
				tbarOpr.push('->');
				tbarOpr.push(new Ext.form.TextField( {
					id : 'certSet_name',
					emptyText : '请输入证书名称',
					enableKeyEvents : true,
					listeners : {
						specialkey : function(field, e) {
							if (e.getKey() == Ext.EventObject.ENTER) {
								listView.queryResItem();
							}
						}
					},
					width : 150
				}));
				tbarOpr.push('-');
				tbarOpr.push({
					text : '查询',
					iconCls : 'previewIcon',
					handler : function() {
						listView.queryResItem();
					}
				}, '-', {
					text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						listView.queryResItem();
					}
				});
			}
			return tbarOpr;
		},
		
		queryResItem : function(v) {
			//if(!v) v = Ext.getCmp('page').pageSize;
		    store.load( {
				params : {
					"page.start" : 0,
					"page.limit" : 20
				}
			});
		},
		clearForm : function(pForm) {
			var formItems = pForm.items['items'];
		    for (i = 0; i < formItems.length; i++) {
		        element = formItems[i];
		        element.setValue('');
		        element.reset(); // 避免出现红色波浪线
		    };
		},
		
		addInit : function() {
			this.onAddOrEditInit();
			var flag = Ext.getCmp('windowmode').getValue();
			if (typeof (flag) != 'undefined') {
				formPanel.form.getEl().dom.reset();
				Ext.getCmp('chkGroup').eachItem(function(item){
					 item.el.dom.checked =false;
					item.checked=false;
				});
			} else {
				this.clearForm(formPanel.getForm());
			}
			win.setTitle('<center>新增证书到期提醒信息</center>');
			Ext.getCmp('windowmode').setValue('add');
			Ext.getCmp('expireWarn').setValue(true);
			win.show();
		},
		
		editInit : function() {
			var record = grid.getSelectionModel().getSelected();
			if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择您要修改的记录');
				return;
			}
			var exists=false;//定义存在变量
			if(formPanel!=undefined){
				exists=true;
			}else{
				this.onAddOrEditInit();
			}
			formPanel.getForm().loadRecord(record);
			win.setTitle('<center>修改证书到期提醒信息</center>');
			Ext.getCmp('windowmode').setValue('edit');
			var warnType=record.data.warnType;
			if(warnType!=null){//提醒人员不为空时
				var data=warnType.split(',');
				var patternFlag=false;
				if(!exists){
					var checkGroup=Ext.getCmp('chkGroup');
					var items=checkGroup.items;
					for(var j=0;j<items.length;j++){
						patternFlag=false;//初始化变量参数
						for(var i=0;i<data.length;i++){
							if(items[j].inputValue==data[i]){
								patternFlag=true;
								items[j].checked=true;
								flag=true;
							}
						}
						if(!patternFlag){
							items[j].checked=false;
						}
					}
				}else{
					Ext.getCmp('chkGroup').eachItem(function(item){
						patternFlag=false;//初始化变量参数
						for(var i=0;i<data.length;i++){
						 if(item.inputValue==data[i]){
							 patternFlag=true;
				             item.el.dom.checked =true;
				             item.checked = true;
						 }
						}
						if(!patternFlag){//匹配不上
							item.el.dom.checked=false;
				             item.checked =false;
						}
			        });
				}
			}
			win.show();
		},
		
		onAddOrEditInit : function(){
			if(!formPanel){
				formPanel = certSetForm.createFormPanel();
			} 
			if(!win){
				win = certSetForm.createWindow();
			}
		},
		
		subForm : function(url) {
			var mode = Ext.getCmp('windowmode').getValue();
			formPanel.form.submit({
				url : cfg.cxt+url,
				waitTitle : '提示',
				method : 'POST',
				waitMsg : '正在处理数据,请稍候...',
				success : function(form, action) {
					var r = action.result.status;
					if (r == 200){
						win.hide();
						form.reset();
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增成功！');
						else
						    Ext.Mytip.msg('提示', '修改成功！');
						store.reload();
					}else if(r==201){//新增时存在相同的记录
						 Ext.Mytip.msg('提示',action.result.info);
					} else{
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增失败！');
						else
						    Ext.Mytip.msg('提示', '修改失败！');
					}
				},
				failure : bangni.sumbitError
			});
		},
		
		deleteItem : function() {
		   var record = grid.getSelectionModel().getSelected();
	       if (Ext.isEmpty(record)) {
				Ext.Mytip.msg('提示', '请先选择要删除的记录！');
				return;
			}
			Ext.Msg
			   .confirm(
					'请确认',
					'<span style="color:red"><b>提示：</b>你真的要删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt+'/certSet/del.action',
								success : function(response) {
									 var r = Ext.decode(response.responseText);
									 if (r.success) {
									 	if(r.status == 200){
									 		store.reload();
											 Ext.Mytip.msg('提示','删除成功！');
										 } else {
											 Ext.Mytip.msg('提示',r.info);
										 }
									} else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"id" : record.data.id
								}
							});
						}
					});
		}
	}
}();
Ext.onReady(listView.init, listView);